package com.wentao.mall.api

import com.wentao.mall.dao.ProductDao
import com.wentao.mall.entity.ListConverter
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.domain.Example
import org.springframework.data.domain.Sort
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.persistence.*

@RestController
class ProductController(val productDao: ProductDao) {

    @GetMapping("/admin/product/list")
    fun adminList(): Result {
        val list = productDao.findAll()
        return Result.success(list)
    }

    @PostMapping("/admin/product/save")
    fun adminSave(@RequestBody product: Product): Result {
        productDao.save(product)
        return Result.success()
    }

    @PostMapping("/admin/product/delete")
    fun adminDelete(id: Int): Result {
        productDao.deleteById(id)
        return Result.success()
    }

    @GetMapping("/api/product/list")
    fun list(catagoryId: Int?, merchantId: Int?, sort: Int? = 0): Result {

        val exa = Example.of(Product(
            merchantId = merchantId,
            catagoryId = catagoryId,
            price = null
        ))
        val so = when (sort) {
            1 -> Sort.by(Sort.Direction.DESC, "price")
            2 -> Sort.by(Sort.Direction.DESC, "createdDate")
            3 -> Sort.by(Sort.Direction.DESC, "sold")
            else -> Sort.by(Sort.Direction.DESC, "id")
        }

        val productList = productDao.findAll(exa, so)

        return Result.success(productList)
    }

    @GetMapping("/api/product/detail/{id}")
    fun detail(@PathVariable id: Int): Result {
        val product = productDao.getOne(id)
        return Result.success(product)
    }

}

@Entity
data class Product(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int? = null,
    @CreatedDate
    val createdDate: Date? = null,
    val name: String? = null,
    val merchantId: Int? = null,
    val catagoryId: Int? = null,

    val price: Int? = 0,

    val picSmall: String? = null,

    @Convert(converter = ListConverter::class)
    val pics: List<String>? = null,

    @Convert(converter = ListConverter::class)
    val descImgs: List<String>? = null,

    @Convert(converter = ListConverter::class)
    val tags: List<String>? = null,

    val sold: Int = 0,

    val originPrice: String? = null, //原价
)